package com.xinghai.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.system.domain.XhUseVehicleInfoDetails;
import com.xinghai.system.domain.XhVehicleInfoMaterial;
import com.xinghai.system.domain.dto.DeviceDetailDTO;
import com.xinghai.system.domain.vo.XhStaticsReportQueryVo;
import com.xinghai.system.domain.vo.XhVehicleInfoMaterialVO;
import com.xinghai.system.mapper.XhVehicleInfoMaterialMapper;
import com.xinghai.system.service.DingdingOaService;
import com.xinghai.system.service.IXhUseVehicleInfoDetailsService;
import com.xinghai.system.service.IXhVehicleInfoMaterialService;
import com.xinghai.system.util.XHConstant;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.UnknownHostException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用车耗材明细Service业务层处理
 * 
 * @author smy
 * @date 2024-07-25
 */
@Service
public class XhVehicleInfoMaterialServiceImpl extends ServiceImpl<XhVehicleInfoMaterialMapper, XhVehicleInfoMaterial> implements IXhVehicleInfoMaterialService
{
    @Autowired
    private XhVehicleInfoMaterialMapper xhVehicleInfoMaterialMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private DingdingOaService dingdingOaService;

    @Autowired
    private IXhUseVehicleInfoDetailsService xhUseVehicleInfoDetailsService;

    @Value("${material.port}")
    private String PORT;

    @Value("${material.url}")
    private String MATERIAL_URL;
    /**
     * 查询用车耗材明细
     * 
     * @param id 用车耗材明细主键
     * @return 用车耗材明细
     */
    @Override
    public XhVehicleInfoMaterial getInfo(Long id)
    {
        return xhVehicleInfoMaterialMapper.getInfo(id);
    }

    /**
     * 查询用车耗材明细列表
     * 
     * @param xhVehicleInfoMaterial 用车耗材明细
     * @return 用车耗材明细
     */
    @Override
    public List<XhVehicleInfoMaterial> list(XhVehicleInfoMaterial xhVehicleInfoMaterial)
    {
            xhVehicleInfoMaterial.setDelFlag("0");
        return xhVehicleInfoMaterialMapper.list(xhVehicleInfoMaterial);
    }

    /**
     * 新增用车耗材明细
     * 
     * @param xhVehicleInfoMaterial 用车耗材明细
     * @return 结果
     */
    @Override
    public int insert(XhVehicleInfoMaterial xhVehicleInfoMaterial)
    {
        xhVehicleInfoMaterial.setCreateTime(DateUtils.getNowDate());
        return xhVehicleInfoMaterialMapper.insert(xhVehicleInfoMaterial);
    }
    /**
     * 批量新增用车耗材明细
     *
     * @param xhVehicleInfoMaterialList 用车耗材明细
     * @return 结果
     */
    @Override
    public int insertBatch(List<XhVehicleInfoMaterial> xhVehicleInfoMaterialList)
    {
        return xhVehicleInfoMaterialMapper.insertBatch(xhVehicleInfoMaterialList);
    }
    /**
     * 修改用车耗材明细
     * 
     * @param xhVehicleInfoMaterial 用车耗材明细
     * @return 结果
     */
    @Override
    public int update(XhVehicleInfoMaterial xhVehicleInfoMaterial)
    {
        xhVehicleInfoMaterial.setUpdateTime(DateUtils.getNowDate());
        return xhVehicleInfoMaterialMapper.update(xhVehicleInfoMaterial);
    }

    /**
     * 批量删除用车耗材明细
     * 
     * @param ids 需要删除的用车耗材明细主键
     * @return 结果
     */
    @Override
    public int deleteBatch(Long[] ids)
    {
        return xhVehicleInfoMaterialMapper.deleteBatch(ids);
    }

    /**
     * 删除用车耗材明细信息
     * 
     * @param id 用车耗材明细主键
     * @return 结果
     */
    @Override
    public int delete(Long id)
    {
        return xhVehicleInfoMaterialMapper.delete(id);
    }

    /**
     * 导入用车耗材明细信息
     *
     * @param list 用车耗材明细信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public boolean importData(List<XhVehicleInfoMaterial> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            XhVehicleInfoMaterialMapper xhVehicleInfoMaterialMapper = sqlSession.getMapper(XhVehicleInfoMaterialMapper.class);
            list.stream().forEach(item -> xhVehicleInfoMaterialMapper.insert(item));
            // 提交数据
            sqlSession.commit();
            sqlSession.rollback();
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }

    @Override
    public Boolean saveBatchMateial(XhVehicleInfoMaterialVO xhVehicleInfoMaterialVO) {

        if (xhVehicleInfoMaterialVO.getMaterialList().isEmpty()){
            return Boolean.FALSE;
        }
        //删除原有的数据重新保存
        xhVehicleInfoMaterialMapper.deleteByVehicle(xhVehicleInfoMaterialVO);
        //填充用车相关信息
        xhVehicleInfoMaterialVO.getMaterialList().stream().peek(p->{
            p.setVehicleId(xhVehicleInfoMaterialVO.getVehicleId());
            p.setType(xhVehicleInfoMaterialVO.getType());
            p.setCreateBy(xhVehicleInfoMaterialVO.getUserId());
            p.setCreateTime(DateUtils.getNowDate());
        }).collect(Collectors.toList());

        return this.saveBatch(xhVehicleInfoMaterialVO.getMaterialList());
    }

    @Override
    public List<XhVehicleInfoMaterial> getMaterialList(Long vehicleId) {
        LambdaQueryWrapper<XhVehicleInfoMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XhVehicleInfoMaterial::getVehicleId,vehicleId);
        return xhVehicleInfoMaterialMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveList(XhVehicleInfoMaterialVO xhVehicleInfoMaterial) throws UnknownHostException {
        XhUseVehicleInfoDetails xhUseVehicleInfoDetails = new XhUseVehicleInfoDetails();
        xhUseVehicleInfoDetails.setCreateTime(DateUtils.getNowDate());
        xhUseVehicleInfoDetails.setInfoId(xhVehicleInfoMaterial.getVehicleId());
        //耗材明细url填充
        // 获取IP地址
        String url = MATERIAL_URL+":"+PORT;
        String detailUrl = StringUtils.format("{}/equipmentCon?vehicleId={}&type=0",url,xhVehicleInfoMaterial.getVehicleId());
        xhUseVehicleInfoDetails.setComments("自制设备耗材明细：" + detailUrl);
//        xhUseVehicleInfoDetails.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        //耗材需求
        xhUseVehicleInfoDetails.setType(XHConstant.STR_2);
        int insert = xhUseVehicleInfoDetailsService.insert(xhUseVehicleInfoDetails);
        if(insert>0){
            //评论
            try {
                dingdingOaService.addComments(xhVehicleInfoMaterial.getVehicleId());
            } catch (Exception e) {
                log.error("评论耗材明细错误:{}",e);
                return false;
            }
            List<XhVehicleInfoMaterial> materialList = xhVehicleInfoMaterial.getMaterialList();
            materialList.stream().forEach(item ->{
                item.setCreateTime(DateUtils.getNowDate());
                item.setUpdateTime(DateUtils.getNowDate());
                item.setDelFlag(StringPool.ZERO);
                item.setVehicleId(xhVehicleInfoMaterial.getVehicleId());
                item.setType(xhVehicleInfoMaterial.getType());
//                item.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
            });
            //批量保存
            int i = insertBatch(materialList);
            return i>0;
        }

        return false;
    }

    @Override
    public List<DeviceDetailDTO> deviceDetailPage(XhStaticsReportQueryVo xhStaticsReportQueryVo) {
        return xhVehicleInfoMaterialMapper.deviceDetailPage(xhStaticsReportQueryVo);
    }

    /**
     * 导入用车耗材需求人/装车人明细信息
     *
     * @param list 用车耗材明细信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public int importMaterial(List<XhVehicleInfoMaterial> list){
        return xhVehicleInfoMaterialMapper.insertBatch(list);
    }

}
